import React, { useState } from 'react';
import { Card, Typography, Button } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import { TrendCardData } from '../types/trendCard';
import { formatNumber } from '../utils/numberFormat';

const { Title, Text } = Typography;

interface TrendCardProps {
  trend: TrendCardData;
  showSendButton?: boolean;
  onSend?: (trend: TrendCardData) => void;
}

export const TrendCard: React.FC<TrendCardProps> = ({ 
  trend, 
  showSendButton = false, 
  onSend 
}) => {
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);

  // 计算所有数据的最大值和最小值，包括所有数据线
  const allValues = trend.dataLines.flatMap(line => line.data.map(d => d.value));
  const maxValue = Math.max(...allValues);
  const minValue = Math.min(...allValues);
  const range = maxValue - minValue || 1;
  
  // 计算Y轴刻度
  const yAxisLabels = [];
  const steps = 4; // 5个刻度点
  for (let i = 0; i <= steps; i++) {
    const value = maxValue - (i / steps) * range;
    yAxisLabels.push({
      y: 40 + (i / steps) * 80, // Y轴位置分布在40-120之间
      value: formatNumber(value, 2)
    });
  }

  // 生成SVG路径
  const generatePath = (data: { date: string; value: number }[], _color: string) => {
    if (data.length < 2) return '';
    
    const width = 320;
    const padding = 40;
    
    // 生成路径点
    const points = data.map((d, i) => {
      const x = padding + (i / (data.length - 1)) * (width - 2 * padding);
      const y = 40 + ((maxValue - d.value) / range) * 80; // Y轴范围40-120
      return `${x},${y}`;
    });
    
    return `M ${points.join(' L ')}`;
  };

  // 格式化日期显示
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return isNaN(date.getTime()) ? '--' : date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
  };

  return (
    <Card 
      className="w-full max-w-md bg-white shadow-lg border border-gray-200 rounded-lg"
      styles={{ body: { padding: '16px' } }}
    >
      {/* 标题 */}
      <div className="mb-4">
        <Title level={4} className="m-0 text-gray-900 text-center font-bold">
          {trend.title}
        </Title>
      </div>

      {/* 图例和收益率 */}
      <div className="mb-4">
        <div className="flex flex-wrap justify-between items-center gap-2">
          {trend.dataLines.map((line, index) => (
            <div key={index} className="flex items-center space-x-2">
              <div 
                className="w-3 h-0.5 rounded" 
                style={{ backgroundColor: line.color }}
              ></div>
              <Text className="text-sm text-gray-700">{line.name}</Text>
              <Text 
                className={`text-sm font-bold ${
                  line.isPositive ? 'text-red-500' : 'text-green-500'
                }`}
              >
                {line.return}
              </Text>
            </div>
          ))}
        </div>
      </div>

      {/* 趋势图 */}
      <div className="mb-4 bg-gray-50 rounded-lg p-4 relative">
        <svg width="100%" height="160" viewBox="0 0 320 160" className="overflow-visible">
          {/* 网格线 */}
          <defs>
            <pattern id="grid" width="32" height="16" patternUnits="userSpaceOnUse">
              <path d="M 32 0 L 0 0 0 16" fill="none" stroke="#E5E7EB" strokeWidth="0.5"/>
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#grid)" />
          
          {/* Y轴刻度标签 */}
          <g>
            {yAxisLabels.map((label, index) => (
              <text 
                key={index}
                x="35" 
                y={label.y + 4} 
                fill="#9CA3AF" 
                fontSize="12" 
                textAnchor="end"
              >
                {label.value}%
              </text>
            ))}
          </g>
          
          {/* 动态渲染所有数据线 */}
          {trend.dataLines.map((line, lineIndex) => (
            <path
              key={lineIndex}
              d={generatePath(line.data, line.color)}
              fill="none"
              stroke={line.color}
              strokeWidth="2.5"
              strokeLinejoin="round"
              strokeLinecap="round"
            />
          ))}

          {/* Hover交互区域和数据点 */}
          {trend.dataLines[0]?.data.map((point, index) => {
            const x = 40 + (index / (trend.dataLines[0].data.length - 1)) * 240;
            const y = 40 + ((maxValue - point.value) / range) * 80;
            
            return (
              <g key={index}>
                {/* 透明的交互区域 */}
                <rect
                  x={x - 8}
                  y={40}
                  width={16}
                  height={80}
                  fill="transparent"
                  style={{ cursor: 'pointer' }}
                  onMouseEnter={() => setHoverIndex(index)}
                  onMouseLeave={() => setHoverIndex(null)}
                />
                
                {/* Hover时显示的数据点和垂直线 */}
                {hoverIndex === index && (
                  <>
                    {/* 垂直线 */}
                    <line
                      x1={x}
                      y1={40}
                      x2={x}
                      y2={120}
                      stroke="#8884d8"
                      strokeWidth="1"
                      strokeDasharray="2,2"
                    />
                    {/* 数据点 */}
                    <circle
                      cx={x}
                      cy={y}
                      r="3"
                      fill={trend.dataLines[0].color}
                      stroke="white"
                      strokeWidth="1"
                    />
                  </>
                )}
              </g>
            );
          })}
        </svg>
        
        {/* X轴时间标签 - 左下角和右下角 */}
        <div className="flex justify-between text-xs text-gray-400 mt-2 px-5">
          <span>{formatDate(trend.dateRange.start)}</span>
          <span>{formatDate(trend.dateRange.end)}</span>
        </div>

        {/* Hover时显示的高亮日期 */}
        {hoverIndex !== null && trend.dataLines[0]?.data[hoverIndex] && (
          <div 
            className="absolute text-xs text-gray-600 bg-white px-2 py-1 rounded shadow-sm border"
            style={{
              left: `${40 + (hoverIndex / (trend.dataLines[0].data.length - 1)) * 240 - 20}px`,
              top: '10px',
              transform: 'translateX(-50%)'
            }}
          >
            {formatDate(trend.dataLines[0].data[hoverIndex].date)}
          </div>
        )}
      </div>

      {/* 发送按钮 */}
      {showSendButton && (
        <div className="mt-4 pt-3 border-t border-gray-100">
          <Button 
            type="primary" 
            block 
            icon={<SendOutlined />}
            onClick={() => onSend?.(trend)}
            className="bg-blue-500 hover:bg-blue-600"
          >
            发送给客户
          </Button>
        </div>
      )}
    </Card>
  );
}; 